/*
* 1.根据报表 id 查询权限列表，翻页
* 2.点击编辑，或者新增，打开侧滑（不添加自定义人员）
* */
import React from "react";
import { Button, Badge, Modal, Form, Input, Icon, Popover } from 'antd';
import { connect } from 'react-redux';
import SlideFrame from 'components/slide-frame';
import ReportDistributionService from "containers/data-center/report-distribution/report-distribution.service";
import ReportDistributionMaintain from "containers/data-center/report-distribution/edit-report-permission";
import { messages } from "share/common";
import menuRoute from "routes/menuRoute";
import {
  reportPermissionModel,
  DEFAULT_GRANT,
  DEFAULT_PERMISSION,
  APP_REPORT_ARRAY,
  WEB_PERSONAL_REPORT_ID,
} from "containers/data-center/report-distribution/report-permission.model";
import 'styles/data-center/report-distribution/report-distribution-details.scss';
import ResizeTable from 'components/resize-table';
import { LanguageInput } from 'components/index';

const FormItem = Form.Item;

class ReportDistributionDetails extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isNewEnable: false,
      loading: false,
      newReport: false,
      modelKey: 1,
      data: [],
      reportObj: {
        reportCode: "",
        reportUrl: "",
        reportName: "",
        reportDesc: "",
        i18n: {},
      },
      pagination: {
        total: 0,
        current: 1,
        page: 0,
        pageSize: 10,
      },
      //报表权限列表
      columns: [
        //序号
        {
          title: messages("common.sequence"),
          dataIndex: 'index',
          width: '6%'
        },
        {
          title: messages('report-distribution.key1'/*报表名称*/),
          dataIndex: "reportName",
          render: value => {
            return <Popover placement="topLeft" content={value}>{value}</Popover>
          }
        },
        {
          title: messages('report-distribution.key9'/*说明*/),
          dataIndex: "remark",
          render: value => {
            return <Popover placement="topLeft" content={value}>{value}</Popover>
          }
        },
        {
          title: messages('data-center.key37')/*指定人员*/,
          dataIndex: "_grantName",
          render: value => {
            return <Popover placement="topLeft" content={value}>{value}</Popover>
          }
        },
        {
          title: messages('data-center.key41')/*数据范围*/,
          dataIndex: "_permissionName",
          render: value => {
            return <Popover placement="topLeft" content={value}>{value}</Popover>
          }
        },
        {
          title: messages('report-distribution.key8'/*分配日期*/),
          dataIndex: "date",
        },    //分配日期
        {
          title: messages("common.column.status"),
          dataIndex: "enable",
          width: '12%',
          render: status => ( //状态
            <Badge status={status ? 'success' : 'error'}
                   text={status ? messages('report-distribution.key10'/*启用*/) : messages('report-distribution.key11'/*未启用*/)}/>
          )
        },
        {
          title: messages("common.operation"),
          key: 'operation',
          width: '12%',
          render: (text, record) => (
            //编辑
            <span>
            <a onClick={(e) => this.handleEdit(e, record)}>
              {messages("common.edit")}
            </a>&nbsp;&nbsp;&nbsp;
              <a onClick={(e) => this.handleDetail(e, record)}>
              {messages("common.detail")}
            </a>
          </span>)
        }   //操作
      ],
      showSlideFrame: false,
      showSlideFrameContent: {
        isNew: true,
        reportId: props.params.id
      },
      //权限范围
      dataAreaOptions: [],
      ReportDistributionDetail: menuRoute.getRouteItem('data-report-distribution-detail', 'key').url,
      ReportDistribution: menuRoute.getRouteItem('data-report-distribution', 'key'),
    }
  }

  componentDidMount() {
    this.getList();
    this.setIsNewEnable();
    this.getReportDetail();
  }

  setIsNewEnable = () => {
    let { profile } = this.props;
    if (profile['advanceFunctions'] && profile['advanceFunctions'].indexOf && profile['advanceFunctions'].indexOf("280002000100") > -1) {
      this.setState({
        isNewEnable: true
      })
    } else {
      this.setState({
        isNewEnable: false
      })
    }
  };

  getReportDetail = () => {
    let params = {
      id: this.props.params.id,
    };
    ReportDistributionService.getReportDetail(params)
      .then(res => {
        this.setState({
          reportObj: res.data,
        })
      })
  };
  //获取报表分配的权限
  getList = () => {
    let { pagination } = this.state;
    let params = {
      id: this.props.params.id,
      page: pagination.page,
      size: pagination.pageSize
    };
    this.setState({
      loading: true
    });
    ReportDistributionService.getPermissionList()
      .then((data) => {
        this.setState({
          dataAreaOptions: data
        });
        //此接口返回后，需要进行数据处理，依赖于一个值列表，缓存在前端
        ReportDistributionService.getReportGrantList(params)
          .then((response) => {
            pagination.total = Number(response.headers['x-total-count']);
            this.setState({
              data: response.data,
              pagination,
              loading: false
            })
          })
          .catch(() => {
            this.setState({
              loading: false
            });
          });
      });
  };
  //分页点击
  onChangePager = (pagina, filters, sorter) => {
    let { pagination } = this.state;
    Object.assign(pagination, {
      current: pagina.current,
      page: pagina.current - 1,
      pageSize: pagina.pageSize
    });
    this.setState({
      pagination
    }, () => {
      this.getList();
    })
  };

  //新增报表权限
  createNewDistribution = () => {
    let { tenant, params } = this.props;
    let reportId = params.id;
    let reportIdNum = Number(reportId);
    let newPermission = Object.assign({}, reportPermissionModel, {
      grant: [],
      permission: [],
      remark: "",
      tenantId: tenant.id,
      reportName: params.name,
      sourceReportId: reportId
    });

    if (APP_REPORT_ARRAY.includes(reportIdNum)) {
      newPermission._grant = DEFAULT_GRANT[reportIdNum].value;
      newPermission._grantName = DEFAULT_GRANT[reportIdNum].name;
      newPermission._permission = DEFAULT_PERMISSION[reportIdNum].value;
      newPermission._permissionName = DEFAULT_PERMISSION[reportIdNum].name;
    }
    if (reportIdNum === WEB_PERSONAL_REPORT_ID) {
      newPermission._permission = DEFAULT_PERMISSION[reportIdNum].value;
      newPermission._permissionName = DEFAULT_PERMISSION[reportIdNum].name;
    }

    this.setState({
      showSlideFrame: true,
      showSlideFrameContent: {
        reportId,
        isNew: true,
        dataAreaOptions: this.state.dataAreaOptions,
        reportDetail: newPermission,
      },
    })
  };
  //编辑报表权限
  handleEdit = (e, record) => {
    this.getReportPermissionDetail(record)
  };
  //获取权限详情（编辑时用）
  getReportPermissionDetail = (record) => {
    let obj = {
      id: record.id,
    };
    const { params } = this.props;
    this.setState({
      loading: true
    });

    if (record.grantDes && record.grantDes === "user") {
      //只有当是自定义用户的时候，才传；不传会把所有人查询出来，效率低
      obj.grantCode = "user";
    }
    if (record.grantDes && record.grantDes === "userGroup") {
      obj.grantCode = "userGroup";
    }


    ReportDistributionService.getPermissionList()
      .then((data) => {
        ReportDistributionService.getReportPermissionDetail(obj)
          .then(res => {
            this.setState({
              loading: false,
              showSlideFrame: true,
              showSlideFrameContent: {
                isNew: false,
                reportId: params.id,
                dataAreaOptions: this.state.dataAreaOptions,
                reportDetail: res.data,
              }
            })
          })
          .catch(() => {
            this.setState({
              loading: false
            });
          })
      });
  };
  //进入详情
  handleDetail = (e, record) => {
    let url = this.state.ReportDistributionDetail;
    url = url.replace(":id", this.props.params.id);
    url = url.replace(":permission_id", record.id);
    url = url.replace(":permission_user", record.grantDes);
    this.context.router.push(url)
  };

  //关闭侧滑
  closeSlide = () => {
    this.refs.form.form.onCancel();
  };

  handleCloseNewSlide = (params) => {
    this.getList();
    this.setState({
      showSlideFrame: false,
      isNew: false
    })
  };
  //返回
  back = () => {
    this.context.router.push(this.state.ReportDistribution.url)
  };
  showAddReport = () => {
    this.setState({
      newReport: true,
    })
  };
  //监听表单值
  handleFormChange = () => {
    //有多语言慎用
  };

  hideAddReport = () => {
    this.props.form.resetFields();
    this.setState({
      newReport: false
    })
  };
  //更新
  addReport = (e) => {
    e.preventDefault();
    let { reportObj } = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        Object.assign(reportObj, {
          reportCode: values.reportCode,
          reportUrl: values.reportUrl
        });
        this.updateReport(reportObj);
      }
    })
  };
  updateReport = (report) => {
    this.setState({
      loading: true,
    });
    ReportDistributionService.updateReport(report)
      .then((response) => {
        this.setState({
          loading: false,
        });
        this.props.form.resetFields();
        this.hideAddReport();
      })
      .catch((err) => {
        this.setState({
          loading: false,
        })
      })
  };
  i18nChange = (name, i18nName) => {
    const { reportObj } = this.state;
    reportObj.reportName = name;
    if (!reportObj.i18n) {
      reportObj.i18n = {};
    }
    reportObj.i18n.reportName = i18nName
  };
  i18nDescChange = (name, i18nName) => {
    const { reportObj } = this.state;
    reportObj.reportDesc = name;
    if (!reportObj.i18n) {
      reportObj.i18n = {};
    }
    reportObj.i18n.reportDesc = i18nName
  };

  render() {
    const {
      isNewEnable, reportObj, data, pagination, columns, loading, showSlideFrame,
      showSlideFrameContent
    } = this.state;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14, offset: 1 },
    };
    const { getFieldDecorator } = this.props.form;
    let className = (!isNewEnable) ? 'edit-report hide' : "edit-report";
    return (
      <div className="report-distribution-details-wrap">
        <div className="table-header">
          <div className="table-header-title">
            {messages("common.total", { total: pagination.total ? pagination.total : '0' })}
          </div>
          {/* 共搜索到total条数据 */}
          <div className="table-header-buttons">
            <Button type="primary" onClick={this.createNewDistribution}>
              {messages('report-distribution.key12'/*新建分配*/)}
            </Button>
            {reportObj.reportType === "SD" && <span className={className}
                                                    onClick={this.showAddReport}> {messages('data-center.key54')/*编辑报表*/}
              </span>}
          </div>
        </div>
        <ResizeTable
          columns={columns}
          dataSource={data}
          pagination={pagination}
          loading={loading}
          rowKey={record => record.id}
          bordered
          onChange={this.onChangePager}
        />
        <div style={{ fontSize: 14, margin: '20px 0', }}>
          <a onClick={this.back}>
            <Icon type="rollback"/>{messages("common.back")/*返回*/}
          </a>
        </div>
        <SlideFrame
          title={showSlideFrameContent.isNew ? messages('report-distribution.key12'/*新建分配*/) : messages('report-distribution.key13'/*编辑分配*/)}
          show={showSlideFrame}
          content={ReportDistributionMaintain}
          onClose={this.closeSlide}
          afterClose={this.handleCloseNewSlide}
          params={showSlideFrameContent}
          hasFooter={true}
          ref="form"
        />
        <Modal
          key={this.state.modalKey}
          closable
          width={600}
          className="create-report-modal"
          title={messages('data-center.key54')/*编辑报表*/}
          visible={this.state.newReport}
          footer={null}
          onCancel={this.hideAddReport}
          destroyOnClose={true}
        >
          <Form onSubmit={this.addReport} onChange={this.handleFormChange}>
            <FormItem
              {...formItemLayout}
              label={messages('data-center.key33')/*报表名称*/}
              colon={true}>
              {getFieldDecorator('reportName', {
                initialValue: reportObj.reportName,
                rules: [
                  {
                    required: true,
                    message: messages("common.please.enter")
                  }
                ]
              })(
                <div>
                  <LanguageInput
                    key={1}
                    name={reportObj.reportName}
                    i18nName={reportObj.i18n ? reportObj.i18n.reportName : null}
                    isEdit={reportObj.id}
                    nameChange={this.i18nChange}
                  />
                </div>
              )
              }
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={messages('data-center.key51')/*报表描述*/}
              colon={true}>
              {getFieldDecorator('reportDesc', {
                initialValue: reportObj.reportDesc,
                rules: [
                  {
                    required: true,
                    message: messages("common.please.enter")
                  }
                ]
              })(
                <div>
                  <LanguageInput
                    key={2}
                    name={reportObj.reportDesc}
                    i18nName={reportObj.i18n ? reportObj.i18n.reportDesc : null}
                    isEdit={reportObj.id}
                    nameChange={this.i18nDescChange}
                  />
                </div>
              )
              }
            </FormItem>

            <FormItem
              {...formItemLayout}
              label={messages('data-center.key52')/*报表代码*/}
              colon={true}>
              {getFieldDecorator('reportCode', {
                initialValue: reportObj.reportCode,
                rules: [
                  {
                    required: true,
                    message: messages("common.please.enter")
                  }
                ]
              })(
                <Input disabled placeholder={messages("common.please.enter")}/>)
              }
            </FormItem>

            <FormItem
              {...formItemLayout}
              label={messages('data-center.key53')/*URL*/}
              colon={true}>
              {getFieldDecorator('reportUrl', {
                initialValue: reportObj.reportUrl,
                rules: [
                  {
                    required: true,
                    message: messages("common.please.enter")
                  }
                ]
              })(
                <Input placeholder={messages("common.please.enter")}/>)
              }
            </FormItem>
            <div className="role-list-from-footer">
              <Button onClick={this.hideAddReport}>
                {messages('common.cancel')}
              </Button>
              &nbsp;&nbsp;&nbsp;
              <Button type="primary"
                      htmlType="submit"
                      loading={loading}>
                {messages('common.save')}
              </Button>
            </div>
          </Form>
        </Modal>
      </div>
    );
  }
}

ReportDistributionDetails.contextTypes = {
  router: React.PropTypes.object
};
const WrappedReportDistributionDetails = Form.create()(ReportDistributionDetails);

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
    profile: state.login.profile,
  }
}

export default connect(mapStateToProps)(WrappedReportDistributionDetails);

